#!/usr/bin/env bash
rm -f trustedkeys
rm -f unbound-host.conf
rm -f recursor.trustedkeys.lua
rm -f recursor.forward-zones-file

for zone in $(grep 'zone ' named.conf  | cut -f2 -d\") addzone.com
do
	if [ "${zone: 0:16}" != "secure-delegated" ] && [ "$zone" != "stest.com" ] && [ "$zone" != "addzone.com" ]
	then
		drill -p $port -o rd -D dnskey $zone @$nameserver | grep $'DNSKEY\t257' | grep -v 'RRSIG' | grep -v '^;' | grep -v AwEAAarTiHhPgvD28WCN8UBXcEcf8f >> trustedkeys
	fi
	echo "stub-zone:" >> unbound-host.conf
	echo "  name: $zone" >> unbound-host.conf
	echo "  stub-addr: $nameserver@$port" >> unbound-host.conf
	echo "" >> unbound-host.conf

	echo "$zone=$nameserver:$port" >> recursor.forward-zones-file
done

echo "server:" >> unbound-host.conf
echo "  do-not-query-address: 192.168.0.0/16" >> unbound-host.conf
echo '  trust-anchor-file: "trustedkeys"' >> unbound-host.conf
echo '  trust-anchor-signaling: no' >> unbound-host.conf

#if [ -e trustedkeys ]
#then
#  cat trustedkeys | grep -c '.' # because wc -l is not portable enough!
#fi

ldns-key2ds -n trustedkeys | awk -F '\t' '{print "addTA(\""$1"\", \""$5"\")"}' > recursor.trustedkeys.lua